import React from 'react';
import { Form, Drawer, Input, InputNumber, Tree, Button, message, Spin, Table, Select, DatePicker,Checkbox } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import { getTenantPlatformSetting } from '@/services/platformManagement';
import { modelListTenant, updateModelListTenant } from '@/services/languageModel';

const { TreeNode } = Tree;

const moduleNameList = ["robot",'moduleKefu','moduleTicket','largeLanguage'];
const qaNameList = ["qaKnowledge",'atlasKnowledge','dialogKnowledge','docKnowledge']

class TenantAdd extends React.Component {
  state = {
    accountData: [],
    visible: false,
    row: null,
    menuTree: [],
    checkedKeys: [],
    loading: true,
    platformSetting:{},
    allKfCenterChildrenIds:[],
    platformSettingId:"",
    modelList:[]
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  initData = (row) => {
    this.getPlatformSetting()
    if (row) {
      this.getMenus(row);
      this.getModelListByTenant(row)
    } else {
      this.getMenusByAdmin();
      this.getModelList()
    };
    this.setState({
      visible: true,
      row: row,
      loading: row ? true : false,
    })
  }

  setData = data => {
    const moduleList = []
    const qaList = []
    for(const key in data.sysPlatformSetting){
      const item = data.sysPlatformSetting[key]
      if(moduleNameList.indexOf(key) != -1 && item == 1){
        moduleList.push(key)
      }
      if(qaNameList.indexOf(key) != -1 && item == 1){
        qaList.push(key)
      }
    }
    this.props.form.setFieldsValue({
      name: data.name,
      username: data.username,
      reviewStatus: data.reviewStatus,
      validity: data.validity?moment(data.validity):undefined,
      remarks: data.remarks,
      tenantType:data.tenantType,
      robotNums: data.robotNums,
      module:moduleList,
      qaType:qaList,
      atlasNums:data.atlasNums,
      dialogNums:data.dialogNums,
      docNums:data.docNums,
      qaNums:data.qaNums,
      replyLimitTimes:data.replyLimitTimes
    });
   
    this.setState({ loading: false,platformSettingId:data.sysPlatformSetting.id });
  }

  getMenusByAdmin = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tenantManagement/getMenuTreeByAdmin',
      payload: { id: 0 },
      callback: res => {
        this.setState({ menuTree: res ? res : [] }, () => {
          this.getSelectMenu(res ? res : []);
        })
      },
    });
  }

  getMenus = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tenantManagement/getMenuTree',
      payload: { id: row.id },
      callback: res => {
        this.setState({ menuTree: res.tree ? res.tree : [] }, () => {
          this.getSelectMenu(res.tree);
          this.setData(res);
        })
      },
    });
  }

  onCheck = (checkedKeys, info) => {
    this.setState({ checkedKeys });
  };

  onClose = () => {
    this.props.form.resetFields();
    this.setState({
      visible: false,
      accountData: [],
      row: null,
      checkedKeys: [],
      loading: true,
      platformSetting:{},
      allKfCenterChildrenIds:[],
      platformSettingId:""
    })
  }

  onSubmit = () => {
    const { accountData, row, checkedKeys,platformSettingId,platformSetting,modelList } = this.state;
    this.props.form.validateFields((errors, values) => {
      if (!errors) {
        if (!checkedKeys || checkedKeys.length === 0) {
          return message.error('请选择功能权限');
        };
        let modelError = [];
        for(const item of modelList){
          if(item.dateType == undefined || item.dateType == null){
            modelError.push(item)
          }
          if(item.dateType != 0 && (item.replyLimitTimes == undefined || item.replyLimitTimes == null)){
            modelError.push(item)
          }
        }
        if(modelError.length > 0){
          message.error("请检查大模型调用次数的填写")
          return false
        }
        let platformSettings = {}
        for(const item of moduleNameList){
          if(values.module.indexOf(item) != -1 && platformSetting[item] == 1){
            platformSettings[item] = 1
          }else{
            platformSettings[item] = 0
          }
        }
        for(const item of qaNameList){
          if(values.qaType.indexOf(item) != -1 && platformSetting[item] == 1){
            platformSettings[item] = 1
          }else{
            platformSettings[item] = 0
          }
        }
        values.platformSetting = platformSettings
        values.llmList = modelList
        delete values.module
        delete values.qaType
        if (row) {
          values.platformSetting.id = platformSettingId
          this.editTenant(values);
        } else {
          this.addTenant(values);
        }
      }
    })
  }

  editTenant = data => {
    const { dispatch } = this.props;
    const { checkedKeys, row } = this.state;
    console.log(data);
    let obj = {
      ...data,
      menus: checkedKeys,
      id: row.id,
      validity: moment(data.validity).format('YYYY-MM-DD'),
    };
    dispatch({
      type: 'tenantManagement/editTenant',
      payload: obj,
      callback: res => {
        // message.info(res.message);
        this.onClose();
        this.props.getList();
      },
    });
  }

  addTenant = data => {
    const { dispatch } = this.props;
    const { checkedKeys } = this.state;
    console.log(data);
    let obj = {
      ...data,
      menus: checkedKeys,
      validity: moment(data.validity).format('YYYY-MM-DD'),
    };
    dispatch({
      type: 'tenantManagement/addTenant',
      payload: obj,
      callback: res => {
        if (res.code === 0) {
          message.info(res.message);
          this.onClose();
          this.props.getList();
        }
      },
    });
  }

  checkFieldForPassword(rule, value, callback) {
    const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
    if (rule.field === 'password') {
      if (value) {
        if (reg.test(value)) {
          if (value.length > 30 || value.length < 6) {
            callback('只可填入8-20位数字和字母组合');
          } else {
            callback();
          }
        } else {
          callback('只可填入8-20位数字和字母组合');
        }
      } else {
        callback('只可填入8-20位数字和字母组合');
      }
    }
  }

  renderTreeNode = data => {
    const { menuTree } = this.state;
    const allKfCenterChildren = this.getAllChildrenNodes(menuTree,'4')
    const allKfCenterChildrenIds = allKfCenterChildren.map(item => item.id)
    allKfCenterChildrenIds.push("4")

    const module = this.props.form.getFieldValue("module")
    const qaType = this.props.form.getFieldValue("qaType")

    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id}
            disableCheckbox={
              module.indexOf("moduleKefu") === -1 
                && 
                (item.id == 36 || allKfCenterChildrenIds.indexOf(item.id) != -1)
              ||
              module.indexOf("moduleTicket") === -1 && item.id == 37
              ||
              qaType.indexOf("atlasKnowledge") === -1 && item.id == 26
              ||
              qaType.indexOf("dialogKnowledge") === -1 && item.id == 27
              ||
              module.indexOf("largeLanguage") === -1 && item.id == 124
            }
          >
            {this.renderTreeNode(item.children)}
          </TreeNode>
        )
      };
      return <TreeNode title={item.name} key={item.id} 
        disableCheckbox={
          module.indexOf("moduleKefu") === -1 
            && 
            (item.id == 36 || allKfCenterChildrenIds.indexOf(item.id) != -1)
          ||
          module.indexOf("moduleTicket") === -1 && item.id == 37
          ||
          qaType.indexOf("atlasKnowledge") === -1 && item.id == 26
          ||
          qaType.indexOf("dialogKnowledge") === -1 && item.id == 27
          ||
          module.indexOf("largeLanguage") === -1 && item.id == 124
        }
      />
    })
  }

  getSelectMenu = data => {
    const that = this;
    let { checkedKeys } = that.state;
    data.map(item => {
      if (item.children && item.children.length > 0) {
        const childrenChecked = item.children.filter(child => child.checked);
        if (childrenChecked.length === item.children.length) {
          checkedKeys.push(item.id);
        };
        that.getSelectMenu(item.children);
      } else {
        if (item.checked) {
          checkedKeys.push(item.id);
        }
      }
    });
    that.setState({ checkedKeys });
  }

  checkField(rule, value, callback) {
    const reg = /^[0-9a-zA-Z_.@]{1,}$/g;
    if (rule.field === 'username') {
      if (value) {
        if (reg.test(value)) {
          if (value.length > 30 || value.length < 6) {
            callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
          } else {
            callback();
          }
        } else {
          callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
        }
      } else {
        callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
      }
    }
  }

  getPlatformSetting = async () => {
    const res = await getTenantPlatformSetting()
    console.log(res);
    this.setState({
      platformSetting:res
    })
  }

  changeModule = (value) => {
    const { checkedKeys,menuTree } = this.state;
    const allKfCenterChildren = this.getAllChildrenNodes(menuTree,'4')
    const allKfCenterChildrenIds = allKfCenterChildren.map(item => item.id)
    allKfCenterChildrenIds.push("4")

    const moduleKefuIndex = value.indexOf('moduleKefu');
    const moduleTicketIndex = value.indexOf('moduleTicket');
    const moduleLanguageIndex = value.indexOf("largeLanguage")
    let newList = checkedKeys
    //无IM 无账号中心-在线技能组-36/无客服中心-4
    if(moduleKefuIndex === -1){
      newList = newList.filter(item => item != 36 && item != 5 && allKfCenterChildrenIds.indexOf(item) === -1)
      // console.log('无IM',newList);
    }
    
    //无工单 无账号中心-工单技能组 -37
    if(moduleTicketIndex === -1){
      newList = newList.filter(item => item != 37 && item != 5 )
      // console.log('无工单',newList);
    }

    //无大语言模型 无机器人交互体验 无文档知识点
    if(moduleLanguageIndex === -1){
      newList = newList.filter(item => item != 124)
      const qaTypeList = this.props.form.getFieldValue("qaType");
      let newQaTypeList = qaTypeList.filter(item => item != 'docKnowledge')
      this.props.form.setFieldsValue({qaType:newQaTypeList})
      // console.log('无大语言',newList);
    }
    this.setState({
      checkedKeys:newList
    })
  }

  changeQaType = value => {
    const { menus,checkedKeys } = this.state;
    let newList = checkedKeys
    //无导图知识点 数据中心-知识导图统计-26
    if(value.indexOf('atlasKnowledge') === -1){
      newList = newList.filter(item => item != 26 && item != 3 )
    }
    //无多轮对话 数据中心-多轮对话统计
    if(value.indexOf('dialogKnowledge') === -1){
      newList = newList.filter(item => item != 27 && item != 3 )
    }
    this.setState({
      checkedKeys:newList
    })
  }

  getAllChildrenNodes = (list, id, arr = []) => {
    for(let i in list) {
      if(list[i].id === id) {
        arr.push(list[i])
        if(list[i].children?.length > 0) {
          this.getChild(list[i].children, arr)
        }
      }else {
        if(list[i].children?.length > 0) {
          this.getAllChildrenNodes(list[i].children, id, arr)
        }
      }
    }
    return arr.filter(v => v.id !== id)
  }

  getChild = (list,  arr) => {
    list.forEach(v => {
      arr.push(v)
      if(v.children) {
        this.getChild(v.children, arr)
      }
    })
  }

  getModelList = async () => {
    const res = await modelListTenant()
    this.setState({
      modelList:res
    })
  }

  getModelListByTenant = async row => {
    const res = await updateModelListTenant({tenantId:row.id})
    this.setState({
      modelList:res
    })
  }

  changeReplyLimitTimes = (value,index) => {
    let { modelList } = this.state;
    modelList[index].replyLimitTimes = value;
    this.setState({
      modelList
    })
  }

  changeDateType = (value,index) => {
    let { modelList } = this.state;
    modelList[index].dateType = value;
    this.setState({
      modelList
    })
  }

  render() {
    const { title } = this.props;
    const { getFieldDecorator,getFieldValue } = this.props.form;
    const { visible, menuTree, row, checkedKeys, loading ,platformSetting,modelList} = this.state
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };

    return (
      <Drawer title={title} visible={visible} closable width={750} onClose={this.onClose} destroyOnClose>
        <Spin spinning={loading}>
          <Form {...formItemLayout} style={{marginBottom:45}}>
            <Form.Item label={'企业名称'}>
              {getFieldDecorator('name', {
                rules: [
                  { required: true, message: '企业名称必填' }
                ],
                getValueFromEvent: event => event.target.value.replace(/\s+/g, '')
              })(
                <Input placeholder={'请填写企业名称'} maxLength={60} autoComplete="off" onPressEnter={this.onSubmit} />
              )}
            </Form.Item>
            <Form.Item label={'账号'}>
              {getFieldDecorator('username', {
                rules: [
                  { required: true, message: '账号必填' },
                  { validator: this.checkField },
                ]
              })(
                <Input placeholder={'请填写账号'} maxLength={60} autoComplete="off" disabled={row ? true : false} onPressEnter={this.onSubmit} />
              )}
            </Form.Item>
            
            {row ? '' : (
              <Form.Item label={'密码'}>
                {getFieldDecorator('password', {
                  rules: [
                    { required: true, message: '密码必填' },
                    { validator: this.checkFieldForPassword, }
                  ]
                })(
                  <Input.Password placeholder={'请填写密码'} maxLength={60} autoComplete="new-password" onPressEnter={this.onSubmit} />
                )}
              </Form.Item>
            )}
            <Form.Item label="有效期">
              {getFieldDecorator('validity', {
                rules: [
                  { required: true, message: '请选择有效期' }
                ],
              })(<DatePicker style={{ width: '100%' }} />)}
            </Form.Item>
            <Form.Item label="功能模块设置">
              {getFieldDecorator("module", {
                rules: [
                  { required: true, message: "请选择应用模块" },
                ],
                initialValue:['robot','moduleKefu','moduleTicket','largeLanguage']
              })(
                <Checkbox.Group onChange={this.changeModule}>
                  <Checkbox value={'robot'} disabled>智能机器人</Checkbox>
                  {
                    platformSetting.moduleKefu == 1 ? (
                      <Checkbox value={'moduleKefu'}>IM客服</Checkbox>
                    ) : ''
                  }
                  {
                    platformSetting.moduleTicket == 1 ? (
                      <Checkbox value={'moduleTicket'}>工单系统</Checkbox>
                    ) : ''
                  }
                  {
                    platformSetting.largeLanguage == 1 ? (
                      <Checkbox value={'largeLanguage'}>大语言模型</Checkbox>
                    ) : ''
                  }
                </Checkbox.Group>
              )}
                
            </Form.Item>
            <Form.Item label="知识类型设置">
              {getFieldDecorator("qaType", {
                rules: [
                  { required: true, message: "请选择知识类型" },
                ],
                initialValue:['qaKnowledge','atlasKnowledge','dialogKnowledge','docKnowledge']
              })(
                <Checkbox.Group onChange={this.changeQaType}>
                  <Checkbox value={'qaKnowledge'} disabled>问答型知识点</Checkbox>
                  {
                    platformSetting.atlasKnowledge == 1 ? (
                      <Checkbox value={'atlasKnowledge'}>导图知识点</Checkbox>
                    ) : ''
                  }
                  {
                    platformSetting.dialogKnowledge == 1 ? (
                      <Checkbox value={'dialogKnowledge'}>多轮对话</Checkbox>
                    ) : ''
                  }
                  {
                    platformSetting.docKnowledge == 1 ? (
                      <Checkbox value={'docKnowledge'} disabled={getFieldValue("module").indexOf("largeLanguage") === -1}>文档型知识点</Checkbox>
                    ) : ''
                  }
                </Checkbox.Group>
              )}
            </Form.Item>
            <Form.Item label={'功能权限'}>
              {getFieldDecorator('menus')(
                <Tree checkable checkedKeys={checkedKeys} onCheck={this.onCheck} style={{ maxHeight: '300px', overflowY: 'auto' }}>
                  {this.renderTreeNode(menuTree)}
                </Tree>
              )}
            </Form.Item>
            <Form.Item label={'应用数量'}>
              <span style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ marginRight: 5 }}>最大可以创建</span>
                {getFieldDecorator('robotNums', {
                  initialValue: 5,
                  rules: [
                    { required: true, message: '应用数量必填' }
                  ],
                })(
                  <InputNumber style={{ width: '100px' }} min={1} precision={0} />
                )}
                <span style={{ marginLeft: 5 }}>个应用</span>
              </span>
            </Form.Item>
            <Form.Item label={'知识点数量'}>
              <span style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ marginRight: 5 }}>最大可以创建</span>
                {getFieldDecorator('qaNums', {
                  initialValue: 1000,
                  rules: [
                    { required: true, message: '知识点数量必填' }
                  ],
                })(
                  <InputNumber style={{ width: '100px' }} min={1} precision={0} />
                )}
                <span style={{ marginLeft: 5 }}>个知识点</span>
              </span>
            </Form.Item>
            <Form.Item label={'多轮数量'}>
              <span style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ marginRight: 5 }}>最大可以创建</span>
                {getFieldDecorator('dialogNums', {
                  initialValue: 50,
                  rules: [
                    { required: true, message: '多轮数量必填' }
                  ],
                })(
                  <InputNumber style={{ width: '100px' }} min={1} precision={0} />
                )}
                <span style={{ marginLeft: 5 }}>个多轮</span>
              </span>
            </Form.Item>
            <Form.Item label={'导图数量'}>
              <span style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ marginRight: 5 }}>最大可以创建</span>
                {getFieldDecorator('atlasNums', {
                  initialValue: 50,
                  rules: [
                    { required: true, message: '导图数量必填' }
                  ],
                })(
                  <InputNumber style={{ width: '100px' }} min={1} precision={0} />
                )}
                <span style={{ marginLeft: 5 }}>个导图</span>
              </span>
            </Form.Item>
            <Form.Item label={'文档数量'}>
              <span style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ marginRight: 5 }}>最大可以创建</span>
                {getFieldDecorator('docNums', {
                  initialValue: 50,
                  rules: [
                    { required: true, message: '文档数量必填' }
                  ],
                })(
                  <InputNumber style={{ width: '100px' }} min={1} precision={0} />
                )}
                <span style={{ marginLeft: 5 }}>个文档</span>
              </span>
            </Form.Item>
            <Form.Item label={'大模型调用次数'}>
            {
              modelList.map((item,index) => {
                return (
                  <div>
                    <label style={{marginRight:5}}>{item.modelName}</label>
                    <Select value={item.dateType} onChange={(value) => this.changeDateType(value,index)} style={{width:100,marginRight:5}}>
                      <Select.Option value={0}>无限制</Select.Option>
                      <Select.Option value={1}>每天</Select.Option>
                      <Select.Option value={2}>每月</Select.Option>
                      <Select.Option value={3}>每年</Select.Option>
                    </Select>
                    {
                      item.dateType == 0 ? <span>调用</span> : (
                        <span>
                          <span style={{ marginRight: 5 }}>最大可以调用</span>
                          <InputNumber style={{ width: '100px' }} min={0} precision={0} value={item.replyLimitTimes} onChange={(value) => this.changeReplyLimitTimes(value,index)} />
                          <span style={{ marginLeft: 5 }}>次</span>
                        </span>
                      )
                    }
                    
                  </div>
                )
              })
            }
              
            </Form.Item>
            <Form.Item label={'备注'}>
              {getFieldDecorator('remarks')(<Input.TextArea placeholder="请输入" rows={5} />)}
            </Form.Item>
          </Form>
        </Spin>
        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={this.onClose} style={{ marginRight: 8 }}>取消</Button>
          <Button onClick={this.onSubmit} type="primary">确定</Button>
        </div>
      </Drawer>
    )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(TenantAdd));
